package com.youlu.campus.monitor.service.impl;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.monitor.entity.WechatMonitor;
import com.youlu.campus.monitor.entity.WechatMonitorPageQuery;
import com.youlu.campus.monitor.repositories.WechatMonitorRepository;
import com.youlu.campus.monitor.service.WechatMonitorService;
import com.youlu.campus.monitor.service.WechatQuestionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 微信监控业务逻辑实现类
 *
 * @author su
 * @date 2025/09/02
 */
@Service
public class WechatMonitorServiceImpl implements WechatMonitorService {

    @Autowired
    private WechatMonitorRepository wechatMonitorRepository;

    @Resource
    private MongoTemplate wechatMonitorMongoTemplate;

    @Autowired
    private WechatQuestionService wechatQuestionService;


    @Override
    public WechatMonitor saveWechatMonitor(WechatMonitor wechatMonitor) {
        // 参数校验（避免空值插入，符合业务规范）
        Assert.notNull(wechatMonitor, "微信监控实体不能为null");
        Assert.hasText(wechatMonitor.getType(), "类型不能为空");
        Assert.hasText(wechatMonitor.getActivityId(), "活动ID不能为空");

        //唯一名称校验
        WechatMonitor wechatMonitorByName = wechatMonitorRepository.findOneByName(wechatMonitor.getName());
        if (Objects.nonNull(wechatMonitorByName) && !wechatMonitorByName.getId().equals(wechatMonitor.getId())) {
            throw new BusinessException("监控名称已存在,不可重复");
        }
        // 执行新增（对应MongoDB insert）
        if (StringUtils.isBlank(wechatMonitor.getId())) {
            wechatMonitor.setCreateTime(LocalDateTime.now());
        } else {
            Optional<WechatMonitor> optional = wechatMonitorRepository.findById(wechatMonitor.getId());
            if (!optional.isPresent()) {
                throw new BusinessException("数据不存在");
            }
            wechatMonitor.setCreateTime(optional.get().getCreateTime());
            wechatMonitor.setUpdateTime(LocalDateTime.now());
        }
        //如果为微信名称null 就默认为名称
        if (StringUtils.isBlank(wechatMonitor.getWechatName())) {
            wechatMonitor.setWechatName(wechatMonitor.getName());
        }
        // 中文逗号转英文逗号 处理
        if (StringUtils.isNotBlank(wechatMonitor.getExcludeUsers())) {
            String excludeUsers = wechatMonitor.getExcludeUsers().replaceAll("，", ",");
            wechatMonitor.setExcludeUsers(excludeUsers);
        }
        if (StringUtils.isNotBlank(wechatMonitor.getWeekday())) {
            String weekday = wechatMonitor.getWeekday().replaceAll("，", ",");
            wechatMonitor.setWeekday(weekday);
        }
        if (StringUtils.isNotBlank(wechatMonitor.getKeywords())) {
            String keywords = wechatMonitor.getKeywords().replaceAll("，", ",");
            wechatMonitor.setKeywords(keywords);
        }
        if (wechatMonitor.getStartTime().isAfter(wechatMonitor.getEndTime())) {
            throw new BusinessException("开始时间不能大于结束时间");
        }
        String wechatName = wechatMonitor.getWechatName().trim();
        if (wechatName.contains(" ")) {
            throw new BusinessException("微信名称不能包含空格");
        }
        wechatName = wechatName.replaceAll("，", ",");
        String[] split = wechatName.split(",");
        split = Arrays.stream(split).distinct().toArray(String[]::new);
        if (split.length > 10) {
            throw new BusinessException("一次配置微信不能超过10个");
        }
        wechatMonitor.setWechatName(String.join(",", split));
        return wechatMonitorRepository.save(wechatMonitor);
    }

    @Override
    public Boolean deleteWechatMonitorById(String id) {
        wechatMonitorRepository.deleteById(id);
        wechatQuestionService.deleteByMonitorId(id);
        return true;
    }

    @Override
    public WechatMonitor getWechatMonitorById(String id) {
        // 参数校验
        Assert.hasText(id, "查询ID不能为空");
        // 执行查询（Optional处理空值，避免空指针）
        Optional<WechatMonitor> existOptional = wechatMonitorRepository.findById(id);
        return existOptional.orElse(null);
    }

    @Override
    public Page<WechatMonitor> findByPage(WechatMonitorPageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getName())) {
            query.addCriteria(Criteria.where("name").regex(pageQuery.getName(), "i"));
        }
        if (StringUtils.isNotBlank(pageQuery.getType())) {
            query.addCriteria(Criteria.where("type").is(pageQuery.getType()));
        }
        if (StringUtils.isNotBlank(pageQuery.getActivityId())) {
            query.addCriteria(Criteria.where("activityId").is(pageQuery.getActivityId()));
        }
        //统计总条数（分页需要先查总数）
        long total = wechatMonitorMongoTemplate.count(query, WechatMonitor.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<WechatMonitor> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = wechatMonitorMongoTemplate.find(query, WechatMonitor.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);

    }

    @Override
    public List<WechatMonitor> findAll() {
        List<WechatMonitor> monitorList = wechatMonitorRepository.findAll();
        return monitorList;
    }
}
    